import './style/index.css'
import {Input,Checkbox,Icon,Button,Tooltip,Modal,message} from 'antd'
import {WeaTools,WeaNewScroll,WeaLocaleProvider} from 'ecCom'
import trim from 'lodash/trim'
import isEqual from 'lodash/isEqual';
const warning = Modal.warning;
const getLabel = WeaLocaleProvider.getLabel;
/**
 * @功能
 */
export default class Main extends React.Component{
	constructor(props) {
		super(props);
		this.state = {
			atitems:[],
			_atitems:[],
			selectUser:[],
			q:''
		}
		const {requestid = -1} = props;
		const params = {requestid};
        WeaTools.callApi('/api/workflow/forward/getReqWfNodeOperators','GET',params).then((data) => {
            let tempatitems = [];
        	const {operators = []} = data;
            operators.map((o)=>{if(!this.arrayContains(tempatitems,o)){tempatitems.push(o)}});
            this.setState({atitems:tempatitems,_atitems:tempatitems.slice(0,100)});
            window.__atdataready = true;
            window.__atdata = tempatitems;
		});
	}
	
	componentWillReceiveProps(nextProps){
		if(nextProps.visible){
			const {atitems} = this.state;
			this.setState({selectUser:[],_atitems:atitems.slice(0,100)});
		}
	}
	
	shouldComponentUpdate(nextProps, nextState) {
		return !isEqual(this.state.atitems,nextState.atitems)||
			   !isEqual(this.state._atitems,nextState._atitems)||
			   !isEqual(this.state.selectUser,nextState.selectUser)||
			   this.state.q !== nextState.q||
			   this.props.visible !== nextProps.visible;
			   
	}
	
	render(){
		const {_atitems=[],selectUser=[],q} = this.state;
		const {visible} = this.props;
		return (
			<div className="wf-ckeditor-wfat">
				<div className="wea-cb-item" onClick={()=>{this.props.showComponent(visible ? '':'WfAt')}}>
					<Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@wijr9c`} placement="topLeft" title={getLabel(124785,"在签字意见框中输入@可直接选择节点参与人")}>
						<span className={`wea-cbi-icon icon-coms-at`}/>
					</Tooltip>
				</div>
				<div className="wfat-content" style={{display:visible?'block':'none'}}>
					<div className="triangle_border_nw"></div>
					<div className="wfat-input">
						<Input ecId={`${this && this.props && this.props.ecId || ''}_Input@nc342i`} type="text" value={q} onChange={this.doSearch} />
						<span className={`wfat-input-search icon-coms-search`}/>
					</div>
					<div className="wfat-list">
						{_atitems.length > 0  ? 
							<WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@2h7xi3`} height={125}>
								<ul>
								{
									_atitems.map((item,ecindex)=>{
										return <li>
													<Checkbox ecId={`${this && this.props && this.props.ecId || ''}_Checkbox@6t8iev@${ecindex}`} checked={this.arrayContains(selectUser,item)} onClick={this.selectedAtUser.bind(this,item)}>
														<span onClick={this.addOneAtToCkeditor.bind(this,item)} style={{cursor:'pointer'}}>{item.data}</span>
													</Checkbox>
											   </li>
									})
								}
								</ul>
							</WeaNewScroll>
							:
							<div className='wfat-no-data'>
								<span className={`wfat-no-data-icon icon-coms-blank`} />
								<span className="wfat-no-data-tip">{getLabel(83553,'暂无数据')}</span>
							</div>
						}
					</div>
					<div className="wfat-footer">
						<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@rtlimn`} onClick={this.addAtToCKEditor} className="ant-btn-1">{getLabel(826,'确定')}</Button>
						<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@lnvn66`} onClick={this.doCancel} className="ant-btn-2">{getLabel(31129,'取消')}</Button>
					</div>
				</div>
			</div>
		)
	}
	
	selectedAtUser(user){
		const {selectUser=[]} = this.state;
		let _selectUser  = selectUser.filter(o=> o.uid !== user.uid);
		if(_selectUser.length === selectUser.length){
			_selectUser.push(user);
		}
		this.setState({selectUser:_selectUser});
	}
	
	addAtToCKEditor = (user) => {
		const {selectUser=[]} = this.state;
		if(selectUser.length === 0){
			message.warning(`${getLabel(385755,'请至少选择一个')}！`,5);
		}else{
			let atHtmlArr  = [];
			selectUser.map(o=>{
				atHtmlArr.push(`<a href="/hrm/HrmTab.jsp?_fromURL=HrmResource&id=${o.uid}" atsome="@${o.uid}" contenteditable='false' style="cursor:pointer;text-decoration:none !important;margin-right:8px;color:#2777c1!important" target="_blank">@${o.data}&nbsp;</a>`);
			});
			this.props.appendHtmlToCKEditor && this.props.appendHtmlToCKEditor(this.appendStyle(atHtmlArr.join('')));
			this.setState({selectUser:[],q:''});
			this.props.showComponent('');
		}
	}
	
	addOneAtToCkeditor(user,e){
		this.props.appendHtmlToCKEditor && this.props.appendHtmlToCKEditor(this.appendStyle(`<a href="/hrm/HrmTab.jsp?_fromURL=HrmResource&id=${user.uid}" atsome="@${user.uid}" contenteditable="false" style="cursor:pointer;text-decoration:none !important;margin-right:8px;color:#2777c1!important" target="_blank">@${user.data}</a>`));
		this.setState({selectUser:[],q:''});
		this.props.showComponent('');
		e.stopPropagation();
	}
	
	appendStyle(info){
		const {editorId} = this.props;
		const instances = window.CK_REF[editorId].getEditor().ui.instances;
		let _wrapped_contents = info;
    	if(instances){
    		const font  = instances.Font['_'].value || 'Microsoft YaHei';
    		const fontsize  = instances.FontSize['_'].value || 12;
    		_wrapped_contents = `<span style="font-family:'${font}';font-size:${fontsize}px" >${info}&nbsp;&#8203;</span>`;
    	}
		return _wrapped_contents;
	}
	
	doCancel = () => {
		this.setState({q:'',selectUser:[]});
		this.props.showComponent('');
	}
	
	arrayContains(selectUser,user){
		return selectUser.filter(o=>o.uid === user.uid).length > 0;
	}
	
	doSearch = (e) => {
		const {_atitems,atitems} = this.state;
		let q  = e.target.value;
		let r = [];
		if(trim(q).length === 0){
			r = r.concat(atitems);
		}else{
			r = atitems.filter(o=>{
				return o.data.indexOf(q) >= 0 || (trim(o.datapy).length > 0 && o.datapy.indexOf(q.toUpperCase()) >= 0 );
			});
		}
		this.setState({_atitems:r.slice(0,100),q:q});
	}
}
